package org.lemon.cla.serviceImp;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Service
@Slf4j // 使用Lombok的日志注解
public class CosUploadServiceImpl {

    private final COSClient cosClient;
    private String bucketName="2025-1333181667";

//    private String cosEndpoint="cos.ap-shanghai.myqcloud.com";

    public CosUploadServiceImpl(COSClient cosClient) {
        this.cosClient = cosClient;
    }

    /**
     * 上传文件到腾讯云COS
     * @param file 前端上传的MultipartFile文件
     * @param uploadPathInCos COS存储桶中的路径前缀，例如 "news-images/", "avatars/"，注意以斜杠结尾
     * @return 文件的公共访问URL
     * @throws IOException 如果文件处理失败
     */
    public String uploadFile(MultipartFile file, String uploadPathInCos) throws IOException {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传文件不能为空");
        }
        // 确保路径前缀以斜杠结尾，如果为null则默认为空字符串（根目录）
        if (uploadPathInCos == null || uploadPathInCos.isEmpty()) {
            uploadPathInCos = "";
        } else if (!uploadPathInCos.endsWith("/")) {
            uploadPathInCos += "/";
        }

        String originalFilename = file.getOriginalFilename();
        String fileExtension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String newFileName = UUID.randomUUID().toString() + fileExtension;

        // 构建对象键 (Object Key)，即文件在COS中的完整路径
        String key = uploadPathInCos + newFileName;

        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(file.getSize());
        objectMetadata.setContentType(file.getContentType()); // 设置文件MIME类型

        // 创建PutObjectRequest对象
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file.getInputStream(), objectMetadata);

        try {
            // 执行文件上传
            cosClient.putObject(putObjectRequest);

            // *** 核心修正：使用 cosClient.getObjectUrl() 获取文件的公共访问URL ***
            // 这个方法会根据COSClient的配置自动生成正确的URL，包括地域、域名等
            String fileUrl = cosClient.getObjectUrl(bucketName, key).toString();

            log.info("文件上传成功，URL: {}", fileUrl);
            return fileUrl;
        } catch (Exception e) {
            log.error("文件上传到COS失败: {}", e.getMessage(), e);
            throw new IOException("文件上传到云存储失败", e);
        }
    }
}
